<template>
  <div class="role-container">
    <el-card>
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.roleName" placeholder="请输入角色名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" border stripe v-loading="loading">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleCode" label="角色编码"></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="warning" size="small" @click="handleAssignPermission(scope.row)">分配权限</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.size"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; text-align: right;"
      ></el-pagination>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="form.roleCode" :disabled="!!form.id"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" rows="3"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="permissionDialogVisible" width="500px">
      <el-tree
        :data="permissionTree"
        :props="{ children: 'children', label: 'name' }"
        show-checkbox
        node-key="id"
        ref="permissionTree"
      ></el-tree>
      <div slot="footer">
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitPermissions" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRolePage, addRole, updateRole, deleteRole, assignRolePermissions, getRolePermissionIds } from '@/api/role'
import { getPermissionTree } from '@/api/permission'

export default {
  name: 'Role',
  data() {
    return {
      searchForm: {
        roleName: '',
        status: null
      },
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      loading: false,
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        roleName: '',
        roleCode: '',
        description: '',
        status: 1
      },
      rules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        roleCode: [{ required: true, message: '请输入角色编码', trigger: 'blur' }]
      },
      submitLoading: false,
      permissionDialogVisible: false,
      permissionTree: [],
      selectedPermissions: [],
      currentRoleId: null
    }
  },
  created() {
    this.loadData()
    this.loadPermissionTree()
  },
  methods: {
    loadData() {
      this.loading = true
      const params = {
        current: this.pagination.current,
        size: this.pagination.size,
        ...this.searchForm
      }
      getRolePage(params).then(res => {
        this.tableData = res.data.records
        this.pagination.total = res.data.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    loadPermissionTree() {
      getPermissionTree().then(res => {
        this.permissionTree = res.data
      })
    },
    handleSearch() {
      this.pagination.current = 1
      this.loadData()
    },
    handleReset() {
      this.searchForm = {
        roleName: '',
        status: null
      }
      this.handleSearch()
    },
    handleAdd() {
      this.dialogTitle = '新增角色'
      this.form = {
        id: null,
        roleName: '',
        roleCode: '',
        description: '',
        status: 1
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑角色'
      this.form = { ...row }
      this.dialogVisible = true
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true
          const api = this.form.id ? updateRole : addRole
          api(this.form).then(() => {
            this.$message.success('操作成功')
            this.dialogVisible = false
            this.loadData()
            this.submitLoading = false
          }).catch(() => {
            this.submitLoading = false
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除该角色吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(row.id).then(() => {
          this.$message.success('删除成功')
          this.loadData()
        })
      })
    },
    handleAssignPermission(row) {
      this.currentRoleId = row.id
      getRolePermissionIds(row.id).then(res => {
        this.selectedPermissions = res.data
        this.permissionDialogVisible = true
        // 在对话框打开后，设置树形组件的勾选状态
        // 只设置叶子节点（type=2的按钮权限），避免父节点被勾选后自动展开所有子节点
        this.$nextTick(() => {
          // 获取所有叶子节点的ID（按钮权限）
          const leafNodeIds = this.getLeafNodeIds(res.data)
          this.$refs.permissionTree.setCheckedKeys(leafNodeIds)
        })
      })
    },
    // 获取叶子节点ID（只返回按钮权限）
    getLeafNodeIds(permissionIds) {
      // 递归查找所有权限节点
      const findPermissions = (tree, ids) => {
        const result = []
        tree.forEach(node => {
          if (ids.includes(node.id)) {
            // 如果是叶子节点（按钮权限，type=2），添加到结果
            if (node.type === 2) {
              result.push(node.id)
            }
          }
          // 递归查找子节点
          if (node.children && node.children.length > 0) {
            result.push(...findPermissions(node.children, ids))
          }
        })
        return result
      }
      return findPermissions(this.permissionTree, permissionIds)
    },
    handleSubmitPermissions() {
      const checkedKeys = this.$refs.permissionTree.getCheckedKeys()
      const halfCheckedKeys = this.$refs.permissionTree.getHalfCheckedKeys()
      const permissionIds = [...checkedKeys, ...halfCheckedKeys]
      
      if (permissionIds.length === 0) {
        this.$message.warning('请至少选择一个权限')
        return
      }
      
      this.submitLoading = true
      assignRolePermissions(this.currentRoleId, permissionIds).then(() => {
        this.$message.success('权限分配成功')
        this.permissionDialogVisible = false
        this.loadData()
        this.submitLoading = false
      }).catch(() => {
        this.$message.error('权限分配失败')
        this.submitLoading = false
      })
    },
    handleSizeChange(val) {
      this.pagination.size = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.pagination.current = val
      this.loadData()
    }
  }
}
</script>

<style scoped>
.role-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}
</style>
